/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package databook.util;

import java.awt.Color;

import prefuse.util.ColorLib;

/**
 *
 * @author zach
 */
public class SimpleTransformFunction {
    private double START_VAL = 0;
    private double END_VAL = 1;
    private int START_COLOR;
    private int END_COLOR;
    private double HIGH_VAL = 1;
    private double LOW_VAL = 0;
    
    public SimpleTransformFunction() {}
    
    public void setStartValue(double val) {
        START_VAL = val;
    }
    
    public void setEndValue(double val) {
        END_VAL = val;
    }
    
    public void setStartColor(int val) {
        START_COLOR = val;
    }
    
    public void setEndColor(int val) {
        END_COLOR = val;
    }
    
    public void setLowValue(double low) {
        //System.out.println("New Low: " + low);
        LOW_VAL = low;
    }
    
    public void setHighValue(double high) {
        //System.out.println("New High: " + high);
        HIGH_VAL = high;
    }
    
    public double getValue(double val) {
        //if (val == HIGH_VAL) System.out.println("Found the big one: " + val + " " + LOW_VAL + " " + HIGH_VAL + " " + START_VAL + " " + END_VAL);
        if (val < LOW_VAL) val = LOW_VAL;
        if (val > HIGH_VAL) val = HIGH_VAL;
        if (HIGH_VAL == LOW_VAL) return START_VAL;
        double diff = (val - LOW_VAL)/(double)(HIGH_VAL - LOW_VAL);  
        //if ((int)val == HIGH_VAL) System.out.println(LOW_VAL + " < " + val + " < " + HIGH_VAL + " => " + START_VAL + " < " + (START_VAL + ((END_VAL - START_VAL)*diff)) + " < " + END_VAL);
        //if (val == HIGH_VAL) System.out.println("Returning: " + (START_VAL + ((END_VAL-START_VAL)*diff)));
        return START_VAL + ((END_VAL - START_VAL)*diff);        
    }
    
    public int getColor(double val) {
        double diff = (val - LOW_VAL)/(double)(HIGH_VAL - LOW_VAL);
        float[] shsb = getHSB(START_COLOR);
        float[] ehsb = getHSB(END_COLOR);
        float[] nhsb = new float[shsb.length];
        
        for (int i = 0; i < ehsb.length; i++) {
            nhsb[i] = (ehsb[i] - shsb[i])*(float)diff + shsb[i];
        }
        int salpha = ColorLib.alpha(START_COLOR);
        int ealpha = ColorLib.alpha(END_COLOR);
        int alpha = (int)((ealpha - salpha)* diff + salpha);
        //if (val >= HIGH_VAL) System.out.println("Alpha: " + alpha);
        return ColorLib.setAlpha(Color.HSBtoRGB(nhsb[0],nhsb[1],nhsb[2]),alpha);        
    }
    
    public void weigh(double val) {
        if (val < LOW_VAL)
            LOW_VAL = val;
        if (val > HIGH_VAL) 
            HIGH_VAL = val;
    }
    
    public double getHighValue() {
        return HIGH_VAL;
    }
    
    public double getLowValue() {
        return LOW_VAL;
    }
    
    public static float[] getHSB(int color) {
        return Color.RGBtoHSB(ColorLib.red(color), ColorLib.green(color), ColorLib.blue(color),null);
    }
}
